var express = require('express');
var bodyParser = require('body-parser')//加的第一句
var path= require('path')
var mongoose = require('mongoose')
var logger=require('morgan')
var cookieParser=require('cookie-parser')
var session=require('express-session')
var mongoStore=require('connect-mongo')(session)//注意引入包的先后顺序
var port = process.env.PORT || 3001
var app = express()
var fs = require('fs')
var dbUrl='mongodb://localhost/imooc'

console.log("进入APP。js")
mongoose.connect(dbUrl)

//models loading
var models_path = __dirname+'/app/models'
var walk =function(path){
	fs
		.readdirSync(path)
		.forEach(function(file){
			var newPath = path +'/'+file
			var stat = fs.statSync(newPath)

			if (stat.isFile()) {
				if (/(.*)\.(js|coffee)/.test(file)) {
					require(newPath)
				}
			}
			else if(stat.isDirectory()){
				walk(newPath)
			}
		})
}
walk(models_path)


app.set('views', './app/views/pages')
app.set('view engine', 'jade')
app.use(bodyParser.json())//改的第五个地方
app.use(express.static(path.join(__dirname, 'public')))//改的第三个位置
app.use(bodyParser.urlencoded({
	extended: true
}))//加的第二句
app.use(cookieParser())
app.use(require('connect-multiparty')())
app.use(session({
	secret:'imooc',
	store:new mongoStore({
		url:dbUrl,
		connection:'sessions'
	})
}))

if ('development'===app.get('env')) {
	app.set('showStackError',true)
	app.use(logger(':method :url :status'))
	app.locals.pretty=true
	mongoose.set('debug',true)
}

require('./config/routes')(app)
//app.localhost.moment = require('moment')//这里老报错就注释掉了
app.listen(port)

console.log('imooc started on port :' + port)

